package com.jnu.myapplication;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.navigation.ui.AppBarConfiguration;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.android.material.navigation.NavigationView;
import com.jnu.myapplication.DataBase.dataManager;
import com.jnu.myapplication.adapter.AccountAdapter;
import com.jnu.myapplication.DataBase.AccountBean;
import com.jnu.myapplication.databinding.ActivityMainBinding;
import com.jnu.myapplication.dialog.BudgetDialog;
import com.jnu.myapplication.dialog.MoreDialog;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, MenuItem.OnMenuItemClickListener {
    ListView todayLv;  //展示今日收支情况的ListView
    ImageView searchIv;
    Button editBtn;
    ImageButton moreBtn;
    //声明数据源
    List<AccountBean> mDatas;
    AccountAdapter adapter;
    int year,month,day;
    //头布局相关控件
    View headerView;
    TextView topOutTv,topInTv,topbudgetTv,topConTv;
    SharedPreferences preferences;
    AccountBean clickBean;
    public static final int CONTEXT_MENU_ID_ADD = 1;
    public static final int CONTEXT_MENU_ID_EDIT = CONTEXT_MENU_ID_ADD+1;
    public static final int CONTEXT_MENU_ID_DELETE = CONTEXT_MENU_ID_ADD+2;
    private NavigationView navigationView;
    private DrawerLayout drawerLayout;
    private ActionBarDrawerToggle mDrawerToggle;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initTime();
        initView();
        preferences = getSharedPreferences("budget", Context.MODE_PRIVATE);
        //添加ListView的头布局
        addLVHeaderView();
        mDatas = new ArrayList<>();
        //设置适配器：加载每一行数据到列表当中
        adapter = new AccountAdapter(this, mDatas);
        todayLv.setAdapter(adapter);
        init();
        drawerLayout=(DrawerLayout)findViewById(R.id.drawer_layout) ;


    }
public void init(){
    Toolbar toolbar=(Toolbar)findViewById(R.id.toolbar);
    navigationView=(NavigationView)findViewById(R.id.myNavigation);
    drawerLayout=(DrawerLayout)findViewById(R.id.drawer_layout);


    mDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar,
            R.string.drawer_open, R.string.drawer_close){
        @Override
        public void onDrawerOpened(View drawerView){super.onDrawerOpened(drawerView);}
        @Override
        public void onDrawerClosed(View drawerView){super.onDrawerClosed(drawerView);}
    };

    mDrawerToggle.setDrawerIndicatorEnabled(false);
    mDrawerToggle.setHomeAsUpIndicator(R.mipmap.more);

    mDrawerToggle.setToolbarNavigationClickListener(v->drawerLayout.openDrawer(GravityCompat.START));
    mDrawerToggle.syncState();//初始化状态
    drawerLayout.setDrawerListener(mDrawerToggle);

    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            Intent intent=new Intent();
            switch (item.getItemId()){
                case R.id.nav_home:
                    drawerLayout.openDrawer(GravityCompat.START);
                    break;
                case R.id.nav_more_btn_info:
                    intent.setClass(getBaseContext(),MonthChartActivity.class);
                    startActivity(intent);
                    break;
                case R.id.nav_more_btn_record:
                    intent.setClass(getBaseContext(),HistoryActivity.class);
                    startActivity(intent);
                    break;
                case R.id.nav_more_btn_setting:
                    intent.setClass(getBaseContext(),SettingActivity.class);
                    startActivity(intent);
                    break;
            }
            item.setChecked(true);
            drawerLayout.closeDrawers();
            return true;
        }
    });
}


    /** 给ListView添加头布局的方法*/
    private void addLVHeaderView() {
        //将布局转换成View对象
        headerView = getLayoutInflater().inflate(R.layout.item_mainlv_top, null);
        todayLv.addHeaderView(headerView);
        //查找头布局可用控件
        topOutTv = headerView.findViewById(R.id.item_mainlv_top_tv_out);
        topInTv = headerView.findViewById(R.id.item_mainlv_top_tv_in);
        topbudgetTv = headerView.findViewById(R.id.item_mainlv_top_tv_budget);
        topConTv = headerView.findViewById(R.id.item_mainlv_top_tv_day);

        topbudgetTv.setOnClickListener(this);
        headerView.setOnClickListener(this);
    }
    /** 初始化自带的View的方法*/
    private void initView() {
        todayLv = findViewById(R.id.main_lv);
        editBtn = findViewById(R.id.main_btn_edit);
        moreBtn = findViewById(R.id.main_btn_more);
        searchIv = findViewById(R.id.main_iv_search);
        editBtn.setOnClickListener(this);
        moreBtn.setOnClickListener(this);
        searchIv.setOnClickListener(this);
        setLVLongClickListener();
    }

    /** 设置ListView的长按事件*/
    private void setLVLongClickListener() {
        todayLv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {  //点击了头布局
                    return false;
                }
                int pos = position-1;
                clickBean = mDatas.get(pos);  //获取正在被点击的这条信息
                //弹出上下文菜单
                registerForContextMenu(view);
                return false;
            }

        });
    }
    @Override
    public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenu.ContextMenuInfo menuInfo) {

        MenuItem menuItemAdd=contextMenu.add(Menu.NONE,CONTEXT_MENU_ID_ADD,CONTEXT_MENU_ID_ADD,this.getResources().getString(R.string.string_menu_add));
        MenuItem menuItemEdit=contextMenu.add(Menu.NONE,CONTEXT_MENU_ID_EDIT,CONTEXT_MENU_ID_EDIT,this.getResources().getString(R.string.string_menu_edit));
        MenuItem menuItemDelete=contextMenu.add(Menu.NONE,CONTEXT_MENU_ID_DELETE,CONTEXT_MENU_ID_DELETE,this.getResources().getString(R.string.string_menu_delete));

        menuItemAdd.setOnMenuItemClickListener(this);
        menuItemEdit.setOnMenuItemClickListener(this);
        menuItemDelete.setOnMenuItemClickListener(this);
    }
    @Override
    public boolean onMenuItemClick(MenuItem menuItem) {

        Intent intent;
        switch(menuItem.getItemId())
        {
            case CONTEXT_MENU_ID_ADD:
                intent = new Intent(this, AddActivity.class);  //跳转界面
                startActivity(intent);
                break;
            case CONTEXT_MENU_ID_EDIT:
                intent=new Intent(this, EditActivity.class);
                int id=clickBean.getId();

                intent.putExtra("id",id);
                startActivity(intent);
                break;
            case CONTEXT_MENU_ID_DELETE:
                AlertDialog.Builder alertDB=new AlertDialog.Builder(this);
                alertDB.setPositiveButton(this.getResources().getString(R.string.string_confirmation), (dialog, which) -> {
                    int click_id = clickBean.getId();
                    //执行删除的操作
                    dataManager.deleteItemFromAccounttbById(click_id);
                    mDatas.remove(clickBean);   //实时刷新，移除集合当中的对象
                    adapter.notifyDataSetChanged();   //提示适配器更新数据
                    setTopTvShow();   //改变头布局TextView显示的内容
                });
                alertDB.setNegativeButton(this.getResources().getString(R.string.string_cancel), (dialog, which) -> {

                });
                alertDB.setMessage(this.getResources().getString(R.string.string_confirm_delete)+"?");
                alertDB.setTitle(this.getResources().getString(R.string.string_hint)).show();
                break;
        }
        return false;
    }
    /* 获取今日的具体时间*/
    private void initTime() {
        Calendar calendar = Calendar.getInstance();
        year = calendar.get(Calendar.YEAR);
        month = calendar.get(Calendar.MONTH)+1;
        day = calendar.get(Calendar.DAY_OF_MONTH);
    }
    // 当activity获取焦点时，会调用的方法
    @Override
    protected void onResume() {
        super.onResume();
        loadDBData();
        setTopTvShow();
    }
    /* 设置头布局当中文本内容的显示*/
    private void setTopTvShow() {
        //获取今日支出和收入总金额，显示在view当中
        float incomeOneDay = dataManager.getSumMoneyOneDay(year, month, day, 1);
        float outcomeOneDay = dataManager.getSumMoneyOneDay(year, month, day, 0);
        String infoOneDay = "今日支出 ￥"+outcomeOneDay+"  收入 ￥"+incomeOneDay;
        topConTv.setText(infoOneDay);
//        获取本月收入和支出总金额
        float incomeOneMonth = dataManager.getSumMoneyOneMonth(year, month, 1);
        float outcomeOneMonth = dataManager.getSumMoneyOneMonth(year, month, 0);
        topInTv.setText("￥"+incomeOneMonth);
        topOutTv.setText("￥"+outcomeOneMonth);

//    设置显示运算剩余
        float bmoney = preferences.getFloat("bmoney", 0);//预算
        if (bmoney == 0) {
            topbudgetTv.setText("￥ 0");
        }else{
            float syMoney = bmoney-outcomeOneMonth;
            topbudgetTv.setText("￥"+syMoney);
        }
    }

    // 加载数据库数据
     private void loadDBData() {
        List<AccountBean> list = dataManager.getAccountListOneDayFromAccounttb(year, month, day);
        mDatas.clear();
        mDatas.addAll(list);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.main_iv_search:
                Intent it = new Intent(this, SearchActivity.class);  //跳转界面
                startActivity(it);
                break;
            case R.id.main_btn_edit:
                Intent it1 = new Intent(this, AddActivity.class);  //跳转界面

                startActivity(it1);
                break;
            case R.id.main_btn_more:
                MoreDialog moreDialog = new MoreDialog(this);
                moreDialog.show();
                moreDialog.setDialogSize();
                break;
            case R.id.item_mainlv_top_tv_budget:
                showBudgetDialog();
                break;
        }
        if (v == headerView) {
            //头布局被点击了
            Intent intent1 = new Intent();
            intent1.setClass(this, MonthChartActivity.class);
            startActivity(intent1);
        }
    }
    /** 显示运算设置对话框*/
    private void showBudgetDialog() {
        BudgetDialog dialog = new BudgetDialog(this);
        dialog.show();
        dialog.setDialogSize();
        dialog.setOnEnsureListener(new BudgetDialog.OnEnsureListener() {
            @Override
            public void onEnsure(float money) {
                //将预算金额写入到共享参数当中，进行存储
                SharedPreferences.Editor editor = preferences.edit();
                editor.putFloat("bmoney",money);
                editor.commit();
                //计算剩余金额
                float outcomeOneMonth = dataManager.getSumMoneyOneMonth(year, month, 0);
                float syMoney = money-outcomeOneMonth;//预算剩余 = 预算-支出
                topbudgetTv.setText("￥"+syMoney);
            }
        });
    }

}